package com.example.farmrental.controller;

import com.example.farmrental.dto.ApiResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传控制器。
 */
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*")
public class FileUploadController {

    /**
     * 图片基本存储路径。
     */
    private static final String UPLOAD_ROOT = "D:/tupian";

    /**
     * 图片上传接口。
     */
    @PostMapping("/upload")
    public ResponseEntity<ApiResponse<Map<String, String>>> uploadImage(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "scope", required = false) String scopeParam) {
        try {
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body(ApiResponse.error("请选择要上传的文件"));
            }

            String contentType = file.getContentType();
            if (contentType == null || (!contentType.equals("image/jpeg") && !contentType.equals("image/png"))) {
                return ResponseEntity.badRequest().body(ApiResponse.error("只支持JPG和PNG格式的图片"));
            }

            if (file.getSize() > 20 * 1024 * 1024) {
                return ResponseEntity.badRequest().body(ApiResponse.error("图片大小不能超过20MB"));
            }

            String scope = (scopeParam == null || scopeParam.isEmpty()) ? "admin" : scopeParam.toLowerCase();
            if (!scope.equals("admin") && !scope.equals("user")) {
                scope = "admin";
            }

            Path scopeDir = Paths.get(UPLOAD_ROOT, scope);
            Files.createDirectories(scopeDir);

            String originalFilename = file.getOriginalFilename();
            String fileExtension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }

            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
            String uniqueId = UUID.randomUUID().toString().substring(0, 8);
            String fileName = timestamp + "_" + uniqueId + fileExtension;

            Path filePath = scopeDir.resolve(fileName);
            Files.copy(file.getInputStream(), filePath);

            String fileUrl = "/images/" + scope + "/" + fileName;

            Map<String, String> result = new HashMap<>();
            result.put("url", fileUrl);
            result.put("fileName", fileName);

            return ResponseEntity.ok(ApiResponse.success("图片上传成功", result));

        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.internalServerError().body(ApiResponse.error("文件上传失败：" + e.getMessage()));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.internalServerError().body(ApiResponse.error("系统错误：" + e.getMessage()));
        }
    }
}